package com.snow.datasource.strategy;

import com.snow.datasource.route.SnowRoutingDataSource;
import com.snow.datasource.strategy.annoation.Strategy;
import com.snow.datasource.strategy.enums.HandleStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 随机策略
 *
 * @Description
 * @Author fanxl
 * @Date 2020/12/23
 **/
@Strategy(value = HandleStrategy.RANDOM)
public class RandomStrategy implements IStrategy , BeanPostProcessor {

    @Autowired
    private SnowRoutingDataSource snowRoutingDataSource;

    @Override
    public String getDataBaseKey() {
        return null;
    }

    @Override
    public String getSlaveKey() {
        int index = ThreadLocalRandom.current().nextInt(snowRoutingDataSource.getDataSourceSlaves().size());
        return snowRoutingDataSource.getDataSourceSlaves().get(index);
    }
}
